import {stateInt} from '../interface/storeInterface'

const state: stateInt = {
    //推送消息
    data: {},
    webSocket: null,
    pingInterval: null
}


const mutations = {
    initWebsocket(state) {
        if (!state.webSocket) {
            state.webSocket = new WebSocket('ws://100.100.100.200:18081/websockets/aibangplc');

            state.webSocket.onopen = function () {
                console.log('通讯开始');

                state.pingInterval = setInterval(() => {
                    if (state.webSocket && state.webSocket.readyState === WebSocket.OPEN) {
                        state.webSocket.send('1');
                    }
                }, 1000 * 60);
            };

            state.webSocket.onmessage = function (e) {
                console.log('收到的数据：', e.data);
                const data = JSON.parse(e.data);
                state.data = data;
                console.log(data);
            };

            state.webSocket.onerror = function () {
                console.log('通讯异常');
            };

            state.webSocket.onclose = function () {
                console.log('连接已断开');
                if (state.pingInterval) {
                    clearInterval(state.pingInterval);
                    state.pingInterval = null;
                }
            };
        }
    },

    closeWebsocket(state) {
        if (state.webSocket) {
            state.webSocket.close();
            state.webSocket = null;
            if (state.pingInterval) {
                clearInterval(state.pingInterval);
                state.pingInterval = null;
            }
        }
    }
};

const actions = {};
const modules = {}


export default {
    namespaced: true,  // 开启命名空间
    state,
    mutations,
    actions
};